package com.tanhua.dubbo.api;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    //圈子-发布动态
    @Override
    public void publishMovement(Movement movement) {
        try {
            //保存动态详情
            //设置PID和发布时间
            movement.setPid(idWorker.getNextId("movement"));
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            //调用timeLineService实现异步处理
            timeLineService.saveTimeLine(movement.getUserId(), movement.getId());
//            //获取好友列表
//            Criteria criteria = Criteria.where("userId").is(movement.getUserId());
//            Query query = Query.query(criteria);
//            List<Friend> friends = mongoTemplate.find(query, Friend.class);
//            try {
//                Thread.sleep(10000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            //循环好友数据，构建好友时间线表
//            for (Friend friend : friends) {
//                MovementTimeLine movementTimeLine = new MovementTimeLine();
//                movementTimeLine.setMovementId(movement.getId());
//                movementTimeLine.setFriendId(friend.getFriendId());
//                movementTimeLine.setCreated(System.currentTimeMillis());
//                mongoTemplate.save(movementTimeLine);
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
    }

    //查询个人动态
    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        //构建查询条件
        Criteria criteria = Criteria.where("userId").is(userId);
        //构建分页和排序
        Query query = Query.query(criteria).skip((page -1 ) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //调用mongoTemplate查询
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0l,movements);
    }

    //查询所有好友动态
    @Override
    public List<Movement> findFriendMovements(Long friendId, Integer page, Integer pagesize) {
        //构建查询条件
        Criteria criteria=Criteria.where("friendId").in(friendId);
        //构建分页和排序
        Query query = Query.query(criteria).skip((page -1 ) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //调用mongoTemplate查询
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //获取动态id集合
        List<ObjectId> movementId = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        //根据动态id查询动态详情
        Query movementQuery =Query.query(Criteria.where("id").in(movementId));
        return mongoTemplate.find(movementQuery,Movement.class);
    }


    //随机获取多条动态数据
    @Override
    public List<Movement> randomMovements(Integer counts) {
        //创建统计对象，设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,
                Aggregation.sample(counts));
        //调用mongoTemplate方法进行统计
        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation,Movement.class);
        //获取统计结果并返回
        return movements.getMappedResults();
    }

    //根据pid数组查询动态数据
    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        //构建查询条件
        Criteria criteria=Criteria.where("pid").in(pids);
        //构建分页和排序
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Movement.class);
    }

    //根据动态id查询
    @Override
    public Movement findById(String movementId) {
       return mongoTemplate.findById(movementId,Movement.class);
    }
}

